#include "stk_cseq.h"
#include <string.h>

using namespace stk;

CSeq::CSeq()
{
    SetType(STK_FD_NAME_CSEQ);
    m_strMethod = "";
    m_strNumber = "";
}

CSeq::CSeq(const CSeq &src)
{
    *this = src;
}

CSeq::CSeq(const char *buf)
{
    SetType(STK_FD_NAME_CSEQ);
    parse(buf, strlen(buf));
}

CSeq::~CSeq()
{
    clear();
}

void CSeq::clear()
{
    m_strMethod = "";
    m_strNumber = "";
}


bool CSeq::isvalid() const
{
    return (!m_strMethod.empty() || !m_strNumber.empty());
}


int32_t CSeq::to_str (string &str)
{
    //str = "";

    if (!isvalid())
    {
        printf("ERRO: <%010d> <%s.ToStr> Invalid Field, \n", GetSession(), GetTypeName());
        return -1;
    }

    str += m_strNumber;

    if (!m_strMethod.empty())
    {
        str += " ";
        str += m_strMethod;
    }

    return 0;
}

int32_t CSeq::parse (const char * szBuf, int nBufLen)
{
    if (!szBuf)
    {
        printf("ERRO: <%010d> <%s.Parse> Invalid Buffer\n", GetSession(), GetTypeName());
        return -1;
    }

    clear();

    char *	method = NULL;
    char *	end    = NULL;

    method = (char *)strchr (szBuf, ' ');        /* SEARCH FOR SPACE */   //TZJ modified for solaris complier 2007.09.08
    end = (char *)szBuf + strlen (szBuf);

    /* SIP协议method不为NULL */
    if (method == NULL)
    {
        m_strNumber.assign(szBuf, strlen (szBuf));
        printf("<%010d> <%s.Parse> Not find Method\n", GetSession(), GetTypeName());
        return 0;
    }

    if (method - szBuf < 1 || end - method < 1)
    {
        printf("ERRO: <%010d> <%s.Parse> Invalid space addr\n", GetSession(), GetTypeName());
        return -1;
    }

    m_strNumber.assign(szBuf, method - szBuf);
    m_strMethod.assign(method + 1, end - method - 1);

    return 0;                     /* ok */
}


CSeq& CSeq::operator = (const CSeq &src)
{
    clear();

    m_strMethod = src.m_strMethod;
    m_strNumber = src.m_strNumber;

    MsgField::operator=(src);

    return *this;
}
